package p03_SingleLinkedList;

public class Utils {
    /**
     * 获取到单链表的节点的个数(如果是带头结点的链表，需求不统计头节点)
     *
     * @param list
     * @return
     */
    public static int getLength(@org.jetbrains.annotations.NotNull HeroList list) {
        HeroNode temp = list.getHead();
        int length = 0;
        if (temp.next == null) {
            return 0;
        }
        while (temp.next != null) {
            length++;
            temp = temp.next;
        }
        return length;
    }

    /**
     * 查找单链表中的倒数第k个结点【新浪面试题】
     *
     * @param k
     * @return
     */
    public static HeroNode getReverse(HeroList list, int k) {
        int length = getLength(list);
        if (length == 0 || k > length || k < 1) {
            return null;
        }
        HeroNode temp = list.getHead().next;
        int i = 0;
        while (true) {
            if (length - i == k) {
                break;
            }
            temp = temp.next;
            i++;
        }
        return temp;
    }
}
